package de.tum.icuproject.persistence.couchdb.select;

import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import de.tum.icuproject.Subscriber;

/**
 * Handles generate id requests
 * @author stefanoturchetta
 *
 */
public abstract class IdGeneratorRequestHandler extends SelectRequestHandler {

	public IdGeneratorRequestHandler(Subscriber subscriber) {
		super(subscriber);
	}
	
	@Override
	protected void onPostExecute(String result) {
		if (result != null) {
			Log.d("RESULT", result);
			int id = deserializeResult(result) + 1;
			this.notifySubscriber(id);
		}
	}
	
	protected abstract void notifySubscriber(int id);

	protected int deserializeResult(String result) {
		JsonParser parser = new JsonParser();
		JsonObject root = parser.parse(result).getAsJsonObject();
		JsonArray rows = root.get("rows").getAsJsonArray();
		// if there is no result
		if (rows.size() == 0) {
			// return the first possible id
			return 1;
		}
		JsonObject firstObj = rows.get(0).getAsJsonObject();
		int key = firstObj.get("key").getAsInt();
		return key;
	}

}
